<template>
  <div class="ueba-h5" :style="{ width: isMobile ? '100%' : '750px' }">
    <el-form label-position="top" class="ruleForm" ref="form" :model="form" :rules="rules">
      <el-row>
        <div v-for="(item, index) in actions" :key="index">
          <!-- 输入框(input) 文本域（textarea）-->
          <el-col v-if="!item.hidden && item.type === 'input'">
            <el-form-item :prop="item.name">
              <span slot="label">
                <span>{{ item.label || "" }}</span>
                <span class="label-info" v-if="item.labelInfo">（ {{ item.labelInfo }} ）</span>
              </span>
              <el-input :type="item.cate" :placeholder="item.placeholder" v-model="form[item.name]"></el-input>
            </el-form-item>
          </el-col>
          <!-- 单选框 -->
          <el-col v-if="!item.hidden && item.type === 'select' && item.cate === 'radio'">
            <el-form-item :prop="item.name">
              <span slot="label">
                <span>{{ item.label || "" }}</span>
                <span class="label-info" v-if="item.labelInfo">（ {{ item.labelInfo }} ）</span>
              </span>
              <el-radio-group v-model="form[item.name][0]">
                <el-radio
                  v-for="(rItem, rIndex) in item.options"
                  :key="rIndex"
                  :style="{ display: 'block' }"
                  :label="rItem.value"
                  :name="item.name"
                >
                  {{ rItem.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- Select 选择器 -->
          <el-col v-if="!item.hidden && item.type === 'select' && item.cate === 'select'">
            <el-form-item :prop="item.name">
              <span slot="label">
                <span>{{ item.label || "" }}</span>
                <span class="label-info" v-if="item.labelInfo">（ {{ item.labelInfo }} ）</span>
              </span>
              <el-select :filterable="item.filterable" v-model="form[item.name]" :placeholder="item.placeholder">
                <el-option
                  v-for="(sItem, sIndex) in item.options"
                  :key="sIndex"
                  :label="sItem.label"
                  :value="sItem.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- checkbox 复选框 -->
          <el-col v-if="!item.hidden && item.type === 'select' && item.cate === 'checkbox'">
            <el-form-item :prop="item.name">
              <span slot="label">
                <span>{{ item.label || "" }}</span>
                <span class="label-info" v-if="item.labelInfo">（ {{ item.labelInfo }} ）</span>
              </span>
              <el-checkbox-group v-model="form[item.name]">
                <el-checkbox
                  v-for="(cItem, cIndex) in item.options"
                  :style="{ display: 'block', 'margin-left': 0 }"
                  :key="cIndex"
                  :label="cItem.label"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <!-- 文件上传 -->
          <el-col v-if="!item.hidden && item.type === 'file'">
            <!-- :label="item.label || ''" -->
            <el-form-item :prop="item.name">
              <span slot="label">
                <span>{{ item.label || "" }}</span>
                <span class="label-info" v-if="item.labelInfo">（ {{ item.labelInfo }} ）</span>
                <el-tooltip
                  effect="dark"
                  content="点击鼠标左键选中要压缩的文件 / 文件夹，单击鼠标右键，在菜单中选择”压缩“即可完成"
                  placement="top"
                  v-else
                >
                  <el-button style="" type="text"
                    >（压缩文件指南<i class="el-icon-question" style="color: #1890ff" />）</el-button
                  >
                </el-tooltip>
              </span>
              <p style="color: #409eff; line-height: 0px">文件最大上传：2G；</p>
              <p style="color: #409eff; line-height: 0px" v-if="item.format && item.format.length > 0">
                <span>格式为：({{ item.format.join() }})</span>
              </p>
              <el-upload
                drag
                :accept="item.format && item.format.join(',')"
                name="files"
                :file-list="fileListData[item.name]"
                :before-upload="beforeUpload"
                :action="getAction()"
                :data="{
                  name: item.name,
                  pass: item.pass,
                  sessionId: sessionId,
                  username: username,
                }"
                :multiple="item.multiple"
                :on-change="
                  (file, fileList) => {
                    fileUploadChange(file, fileList, item.name);
                  }
                "
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
          </el-col>
          <!-- 日期 -->
          <el-col v-if="!item.hidden && item.type === 'datetime' && item.cate === 'datetime'">
            <el-form-item allowClear :prop="item.name">
              <span slot="label">
                <span>{{ item.label || "" }}</span>
                <span class="label-info" v-if="item.labelInfo">（ {{ item.labelInfo }} ）</span>
              </span>
              <el-date-picker show-time format="YYYY-MM-DD HH:mm:ss" v-model="form[item.name]"></el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 按钮 -->
          <el-col v-if="item.type === 'submit'">
            <el-form-item>
              <el-button
                block
                :disabled="child.kind === 'disable' ? true : false"
                :type="child.kind"
                v-for="(child, subIndex) in item.children"
                :key="subIndex"
                @click="onSubmit(child)"
              >
                {{ child.text }}
              </el-button>
            </el-form-item>
          </el-col>
        </div>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import marked from "marked";
import moment from "moment";
import { waterdropGetH5Api, waterdropPostH5Api } from "api/api.js";
import testData from "./testData/h5";
import Cookies from "js-cookie";
let { NODE_ENV } = process.env;
import TestData from "./testData/h5.js";

export default {
  name: "feedbackH5",
  props: {},
  components: {},
  data() {
    return {
      isMobile: false,
      fileListData: {},
      fileKeys: [], //提交给后台的文件名
      sessionId: "",
      username: "",
      form: {},
      copyForm: {}, //提交的时候把form深复制一份给copyForm 解决日期moment格式问题
      rules: {},
      actions: [],
      query: {},
      loading: false,
      actionUrl: {
        cn: "http://mooncell.intra.xiaojukeji.com/moonApi",
        us: "http://mooncell.intra.didiglobal.com/moonApi-ue",
        de: "http://mooncell.intra.didiglobal.com/moonApi-de",
        "cn-pre": "http://pre.mooncell.intra.xiaojukeji.com/moonApi",
        "us-pre": "http://pre.mooncell.intra.didiglobal.com/moonApi-ue",
      },
      fileList: {},
    };
  },
  computed: {},
  mounted() {
    this.isMobile = this.utils.isMobile();
    console.log("isMobile", this.isMobile);
    this.query = this.$route.query;
    this.username = Cookies.get("_sso_username");
    this.sessionId = Cookies.get("CORE_SESSION");
    // this.getData();
    this.getTestData();
  },
  methods: {
    moment,
    getAction() {
      return `${this.actionUrl[NODE_ENV] || "http://mooncell.intra.xiaojukeji.com/moonApi"}/s3/batchUpload`;
    },
    /**
     * @函数功能:正式接口
     * @参数输入:
     * @函数返回:
     */
    getData() {
      this.loading = true;
      let { id, token, username } = this.$route.query;
      waterdropGetH5Api({
        id: id || "",
        token: token || "",
        username: username || "wlliweili_v",
      }).then((res) => {
        this.loading = false;
        this.actions = res.actions;
        this.setDataFormat();
      });
    },
    getTestData() {
      this.actions = TestData.actions;
      console.log(this.actions);
      this.setDataFormat();
    },
    setDataFormat() {
      if (!this.actions) {
        this.$message.warning("获取的数据为Null");
        return;
      }
      this.fileKeys = [];
      this.actions?.forEach((item) => {
        if (item.type === "input" || item.type === "select") {
          //日期 转化成moment格式
          // if (item.cate === "datetime") {
          //   item.value = item.value && this.getDatePicker(item.value);
          // }
          this.$set(this.form, item.name, item.value || ""); //解决不会触发视图更新
          this.setRules(item); //格式化rules规则
        } else if (item.type === "section") {
          item.text.forEach((text) => {
            text.value = text.value.replace(/\n/g, "<br>");
          });
        } else if (item.type === "file") {
          this.fileKeys.push(item.name);
          //文件上传rules规则 是否是必填项
          // this.$set(this.rules, item.name, []);
          let requiredRule = {
            required: item.required,
            message: "请上传文件",
            trigger: "change",
          };
          // this.rules[item.name].push(requiredRule);
          //设置fileListData
          if (item.value && item.value.length > 0) {
            let value = item.value;
            value.forEach((val, index) => {
              val["uid"] = index;
              val["name"] = val.fileName;
            });
            this.$set(this.fileListData, item.name, value);
            this.$set(this.form, item.name, item.pass); //给form 里面的文件上传name属性赋值，解决点击提交时已经提交过的会再次提示你请提交文件上传
            return;
          }

          this.$set(this.fileListData, item.name, []);
        }
      });
      console.log(this.form);
    },
    /**
     * @函数功能:格式化rules
     * @参数输入:
     * @函数返回:
     */
    setRules(item) {
      // this.rules[item.name] = []
      this.$set(this.rules, item.name, []);
      let message = item.type === "input" ? "please input" : "please select";
      let requiredRule = {
        required: item.required,
        message: message,
        trigger: item.cate === "datetime" ? "change" : "blur",
      };
      if (item.type === "input") {
        item.min = item.min ? item.min : 0;
        item.max = item.max ? item.max : 200;
        let rangeRule = {
          min: item.min,
          max: item.max,
          message: `最少${item.min}字，最多${item.max}字`,
          trigger: "blur",
        };
        this.rules[item.name].push(rangeRule);
      }
      this.rules[item.name].push(requiredRule);
    },
    compiledMarkdown(text) {
      return marked(text);
    },
    getDatePicker(value) {
      return this.moment(value, "YYYY-MM-DD HH:mm:ss");
    },
    beforeUpload(file, fileList) {
      let FILE_MAX_SIZE = 1000 * 1000 * 1000 * 2; //(byte)
      if (file.size > FILE_MAX_SIZE) {
        fileList.splice(fileList.indexOf(file), 1);
        this.$message.error("上传的文件不能超过2G,上传失败");
        return false;
      }
    },
    /**
     * @函数功能:文件上传逻辑
     * @参数输入:
     * @函数返回:
     */
    fileUploadChange(file, fileList, uploadCompoentName) {
      console.log(uploadCompoentName);
      // let { file, fileList } = info;
      //文件上传失败
      if (file.status === "error") {
        this.$set(this.form, uploadCompoentName, "");
        this.$message.warning("upload fail");
        return false;
      }
      if (file.response) {
        let data = file.response.data;
        if (!data) {
          this.$set(this.form, uploadCompoentName, "");
          this.$message.warning(file.response.info || "upload fail");

          //解决上传失败，但是下面还是展示上传的列表了
          fileList[fileList.length - 1].status = "error";
          fileList[fileList.length - 1].response = file.response.info;
          return false;
        }
        let name = file.response.data.name;
        this.$set(this.form, uploadCompoentName, file.uid); //给这个文件上传的prop赋值，不然上传文件了，但是会提示请上传文件
        this.fileList[name] = fileList.slice(-1); //这个感觉没用到
      }
      //移除之后清空
      if (fileList && fileList.length == 0) {
        this.$set(this.form, uploadCompoentName, "");
      }
      // else {
      //   this.$set(this.form, uploadCompoentName, file.uid) //给这个文件上传的prop赋值，不然上传文件了，但是会提示请上传文件
      // }
      this.fileListData[uploadCompoentName] = fileList.slice(-1);
    },
    /**
     * @函数功能:文件上传数据格式处理
     * @参数输入:
     * @函数返回:
     */
    fileSubDataHandle() {
      for (let key in this.fileListData) {
        this.copyForm[key] = [];
        let fileList = this.fileListData[key];
        if (fileList.length > 0 && fileList[0].response) {
          //新上传文件的情况 有response字段
          this.copyForm[key].push(fileList[0].response.data.files[0]);
        } else if (fileList.length > 0 && !fileList[0].response) {
          this.copyForm[key].push(this.fileListData[key][0]);
        }
      }
    },
    /**
     * @函数功能:提交给后台接口
     * @参数输入:
     * @函数返回:
     */
    submitH5Data(btnData) {
      this.fileSubDataHandle();
      waterdropPostH5Api({
        id: this.$route.query.id || "",
        token: this.$route.query.token || "",
        action: btnData.name,
        data: this.copyForm,
        fileKeys: this.fileKeys,
      }).then((res) => {
        if (res.success != 0) {
          return;
        }
        this.$message.success(res.info);
        //获取数据 重新渲染界面（回调）
        this.data = res.data;
        window.parent?.postMessage({ res: { ...res, action: btnData.name } }, "*");
        this.setDataFormat();
      });
    },
    /**
     * @函数功能:点击按钮触发逻辑
     * @参数输入:
     * @函数返回:
     */
    onSubmit(btnData) {
      //不需要校验的情况直接提交
      if (!btnData.verify) {
        this.copyForm = { ...this.form };
        this.submitH5Data(btnData);
        return;
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.copyForm = { ...this.form };
          for (let key in this.form) {
            if (this.form[key]._isAMomentObject) {
              this.copyForm[key] = this.moment(this.form[key]).valueOf();
              console.log(this.copyForm[key]);
            }
          }
          this.submitH5Data(btnData);
        } else {
          this.$message.error("有必填项未填写");
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  watch: {},
};
</script>
<style lang="scss" scoped>
.ueba-h5 {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding-bottom: 20px;
  margin: 0 auto;
  min-height: 100%;
  font-size: 14px;
}
.ruleForm {
  margin: 0 20px;
}
.label-info {
  color: #555;
  // line-height:20px;
  font-size: 12px;
  margin-top: 2px;
}
// /deep/ .ant-upload-list-item-card-actions {
//   display:none
// }
</style>
